package com.china08.yxyapi.api.home.weikecheng;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserMark;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.mg.YxyUserFavorRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.yxweike.YxyWeikeService;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.YxyPlayUrlForWeiKechengBuilder;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 微课详情页
 * 
 */
@CrossOrigin
@RestController
public class WeikeDetailController extends YxyApiBaseController {

    @Value("${yxy.res.url}")
    private String yxy_res_url;

    @Autowired
    private MongoTemplate mt;

    @Autowired
    private YxyWeikeService weikeService;

    @Autowired
    private YxyUserFavorRepository favorRepository;

    @Autowired
    private YxyResResourceRepository resourceRepository;

    @Autowired
    private YxyPlayUrlForWeiKechengBuilder builder;

    @ResponseBody
    @RequestMapping(value = "/api_yw/home/weike/detail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "weikeId", required = true) String weikeId, RespModel respModel) {

        YxyProfile profile = getProfile(request, response);

        // 用户属性
        String userId = profile.getId();

        ElasticYxyResResource resResource = weikeService.findOneResource(weikeId);

        Assert.notNull(resResource, "找不到微课，请刷新页面");
        Assert.isTrue(resResource.getIsDelete() != 1 && resResource.getIsDelete() != -1, "微课已删除");

        // 更新pv
        YxyResResource weikeResource = resourceRepository.findById(weikeId);
        weikeResource.setPv(weikeResource.getPv() + 1);
        resourceRepository.save(weikeResource);
        EsResourceUpdateUtil.updateEsResoure(weikeId);
        // 标题
        respModel = new RespModel();
        respModel.title = resResource.getTitle();
        // 上传者名称
        respModel.uploaderName = resResource.getUploaderName();
        // 评分
        respModel.mark = resResource.getMark() == 0 ? 5
                : new BigDecimal(resResource.getMark()).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
        // 封面
        respModel.cover = resResource.getCover();
        // 视频路径
        String url = builder.setResourceId(weikeId).setUserId(userId).setUserVip(Boolean.valueOf(profile.getUserVip()))
                .setResVip(Boolean.valueOf(profile.getResVip())).setViewFrom("weikecheng").build();
        respModel.location = url;
        // yxy_res_url + "/res/browse/" + weikeId;
        // 相关知识点
        List<String> knowNames = resResource.getKnowNames();
        List<String> knowNames2 = new ArrayList<String>();
        for (String knowName : knowNames) {
            knowName = resResource.getStageName() + "/" + resResource.getWeikeSubjectName() + "/" + knowName;
            knowNames2.add(knowName);
        }
        respModel.knowNames = StringUtils.join(knowNames2, ",");
        // 浏览量
        respModel.pv = resResource.getPv();
        // 是否收藏
        if (StringUtils.isNotBlank(userId)) {
            String schoolId = getProfile(request, response).getSchoolId();
            if (StringUtils.isNotBlank(schoolId)) {
                long myfavCount = favorRepository.countByResIdAndUserId(resResource.getId(), userId);
                respModel.ifFavorite = myfavCount > 0 ? true : false;
                // 我的评分
                YxyUserMark mark = mt.findOne(
                        new Query().addCriteria(Criteria.where("resId").is(weikeId).and("userId").is(userId)),
                        YxyUserMark.class);
                Integer myMark = (mark == null ? -1 : mark.getMark());
                respModel.myMark = myMark;
            } else {
                respModel.ifFavorite = false;
                respModel.myMark = -1;
            }
        }

        // 收藏数量
        respModel.favCount = resResource.getFavoriteCount();
        // 已评数量
        Long markCount = mt.count(new Query().addCriteria(Criteria.where("resId").is(weikeId)), YxyUserMark.class);
        respModel.markCount = markCount;
        respModel.duration = YxyResUtil.getDurationString(resResource);
        // 上传时间
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
        respModel.uploadTime = sdFormat.format(resResource.getUploadTime());
        respModel.intro = resResource.getIntro();
        respModel.uploaderName = resResource.getUploaderName();// 上传者名称

        respModel.uploadId = resResource.getUploaderId();
        respModel.stage = resResource.getStage();
        respModel.subject = resResource.getWeikeSubject();
        respModel.isVip = resResource.getIsVip();
        respModel.isHighQualityYx = resResource.getIsHighQualityYx();
        respModel.resVip = Boolean.valueOf(profile.getResVip());
        respModel.roleId = profile.getRoleId();
        // EsResourcePvUpdateUtil.updateEsResoure(weikeId + "_1");
        return respModel;
    }

    // 微课信息
    protected static class RespModel extends YxyApiRespModel {

        public String uploadId;

        public String title;// 微课名称

        public String avatar;// 作者头像

        public String uploaderName;// 上传者名称

        public String uploaderIntro;// 上传者简介

        public float mark;// 评分

        public String cover;// 微课封面

        public String location;// 微课播放路径

        public String knowNames;// 相关知识点

        public Long pv;// 浏览次数

        public boolean ifFavorite;// 是否收藏

        public Long favCount;// 收藏次数

        public Long markCount;// 评价次数

        public String duration;// 时长

        public String uploadTime;// 上传时间

        public String intro;// 微课简介

        public String stage;// 学段

        public String subject;// 学科

        public Integer myMark;// 我的上次评分

        public Boolean isVip = false;

        public Integer isHighQualityYx = 0;

        public Boolean resVip = false;

        public String roleId;
    }

}
